package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.entity.User;
import com.sky.exception.UserNotLoginException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Objects;

/**
 * @projectName: sky-take-out
 * @package: com.sky.service.impl
 * @className: UserServiceImpl
 * @author: Eric
 * @description: TODO
 * @date: 2023/9/26 10:30
 * @version: 1.0
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public UserLoginVO login(String code) {
        // 1.临时凭证 -> 微信校验(微信官网中的校验格式)
        HashMap<String, String> params = new HashMap<>();
        params.put("appid",weChatProperties.getAppid());
        params.put("secret",weChatProperties.getSecret());
        params.put("js_code",code);
        params.put("grant_type","authorization_code");
        String reponseJson = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", params);
        log.info("得到的响应"+reponseJson);
        // 得到的响应{"session_key":"o6lpf\/7id7GrZOg3rnRmrQ==","openid":"oPaZE6Vxfun2AU6jdgPhdhjn5y0I"}
        JSONObject jsonObject = JSON.parseObject(reponseJson);
        String openid = jsonObject.getString("openid");
        if (Objects.isNull(openid)){    // 异常 登录失败
            throw new UserNotLoginException(MessageConstant.LOGIN_FAILED);
        }

        // 2.创建小刘的信息 - 还要和刘姥姥唯一标识去查询做管理 - 检验重复性
        User user = userMapper.selectByOpenid(openid);
        if (Objects.isNull(user)){
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            // 主键返回
            userMapper.insert(user);
        }

        // 3.实现结果的拼装和返回
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setId(user.getId());
        userLoginVO.setOpenid(openid);
        // 3.1创建JWT
        HashMap<String, Object> map = new HashMap<>();
        map.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                map);
        userLoginVO.setToken(token);
        return userLoginVO;
    }
}
